const Controller = require('egg').Controller;

class CommentController extends Controller {
  // 增加评论
  /**
   * @params{toArticle--目标文章ID,toComment--目标评论ID,toAuthor--目标评论人ID,author--评论者ID,content--评论内容,}
   */
  async comment_add() {
    const query = this.ctx.request.body,
          auth = this.ctx.session.user;
    const toArticle= query.aid,
          toComment= query.cid,
          toAuthor= query.uid,
          content= query.content,
          author= auth.id;
    
    try {
      if(toComment && toAuthor) {  // 添加回复
        console.log('15.....add reply', toArticle);
        const reply = await this.ctx.service.comment.reply_add({toArticle, toComment, toAuthor, content, author}),  // 存储回复
              rid = reply._id;
              // console.log('23.....', reply);
        await this.ctx.service.comment.comment_update({toComment, rid});  // 评论表中存入回复集合
      }else {  // 添加评论
        console.log('27.....add comment');
        const comment = await this.ctx.service.comment.comment_add({toArticle, content, author}),  // 存储评论
              cid = comment._id;
        
        await this.ctx.service.article.article_update(toArticle, cid);  // 文章表中存入评论集合
        
      }
      this.ctx.status = 200;
      return this.ctx.body = {
        s: 200,
        m: `ok~`,
        d: {}
      }
    }catch(err) {
      return this.ctx.body = {
        s: 500,
        m: `fail~${err}`,
        d: {}
      }
    }
  }
  // 获取评论列表
  async comment_list() {
    const query = this.ctx.request.body,
          aid = query.aid;
    try {
      const list = await this.ctx.service.comment.comment_list(aid);
      this.ctx.status = 200;
      return this.ctx.body = {
        s: 200,
        m: 'ok~',
        d: list
      }
    }catch(err) {
      return this.ctx.body = {
        s: 500,
        m: `fail~${err}`,
        d: {}
      }
    }
  }
  // 获取回复列表
  async reply_list() {
    const query = this.ctx.request.body,
          cid = query.cid;
    try {
      const list = await this.ctx.service.comment.reply_list(cid);
      this.ctx.status = 200;
      return this.ctx.body = {
        s: 200,
        m: 'ok~',
        d: list
      }
    }catch(err) {
      return this.ctx.body = {
        s: 500,
        m: `fail~${err}`,
        d: {}
      }
    }
  }
}

module.exports = CommentController;